package ru.stepuk.modern.nodes.buffers;

import java.util.Deque;
import java.util.LinkedList;
import java.util.ListIterator;
import javax.swing.ImageIcon;
import ru.stepuk.modern.Model;
import ru.stepuk.modern.Request;

/**
 *
 * @author ivan
 */
public class PriorityQueue extends Buffer {

    {
        icon = new ImageIcon(getClass().getResource("/images/b_prior.png"));
    }

    public PriorityQueue(Model model) {
        super(model);
        container = new LinkedList<Request>();
    }

    @Override
    public void putRequest(Request request) {

        if (!hasFreeSpace()) {
            return;
        }

        if (container.isEmpty() ||
                request.getPriority() <= ((Deque<Request>) container).peekLast().getPriority()) {
            container.add(request);
            return;
        }

        ListIterator<Request> it = container.listIterator();
        while (it.hasNext()) {
            if (request.getPriority() > it.next().getPriority()) {
                container.add(it.previousIndex(), request);
                return;
            }
        }
    }

    @Override
    public Request fetchRequest() {
        return ((Deque<Request>) container).pollFirst();
    }


    @Override
    public void processRequest(Request request) {
        throw new UnsupportedOperationException("Not supported yet.");
    }
}
